package com.soft.admin.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.soft.admin.common.ElementConst;
import com.soft.admin.dto.ComboDTO;
import com.soft.admin.dto.RuleDTO;
import com.soft.admin.dto.RuleDetailDTO;
import com.soft.admin.service.RuleService;
import com.soft.dao.RuleDao;
import com.soft.model.Channel;
import com.soft.model.Rule;
import com.soft.model.RuleDetail;
import com.soft.model.User;
import com.soft.support.PageParam;
import com.soft.support.Pager;
import com.soft.util.DateUtil;
import com.soft.util.FileUtil;
import com.soft.util.JsonUtil;
import com.soft.util.RequestUtil;

@SuppressWarnings("unchecked")
@Component
public class RuleServiceImpl implements RuleService {
	private RuleDao ruleDao;

	@Autowired
	public void setRuleDao(RuleDao ruleDao) {
		this.ruleDao = ruleDao;
	}
	
	@Transactional(readOnly = true)
	public String get(RuleDTO params, PageParam page) {
		List<Criterion> values = new ArrayList<Criterion>();
		values.add(Restrictions.like("title", params.getTitle(), MatchMode.ANYWHERE));
		if (params.getChannel() != -1) {
			values.add(Restrictions.eq("channel.id", params.getChannel()));
		}
		if (params.getState() != -1) {
			values.add(Restrictions.eq("state", params.getState()));
		}
		Pager ruleLst = this.ruleDao.findForPager(Rule.class, 
				new Order[] { Order.desc("level"), Order.desc("releaseDate"), Order.desc("id") }, 
				page.getStart(), page.getLimit(), values);
		Pager pageModel = new Pager();
		pageModel.setTotal(ruleLst.getTotal());
		List<RuleDTO> dtos = new ArrayList<RuleDTO>();
		for (Rule rule : (List<Rule>)ruleLst.getDatas()) {
			RuleDTO dto = new RuleDTO();
			BeanUtils.copyProperties(rule, dto, new String[]{"channel", "user", "releaseDate", "updateDate"});
			dto.setChannel(rule.getChannel().getId());
			dto.setUser(rule.getUser().getId());
			dto.setReleaseDate(DateUtil.format(rule.getReleaseDate()));
			dto.setUpdateDate(DateUtil.format(rule.getUpdateDate()));
			dtos.add(dto);
		}
		pageModel.setDatas(dtos);
		return JsonUtil.toStringFromObject(pageModel);
	}
	
	@Transactional(readOnly = true)
	public String getFile(Integer id) {
		Rule rule = (Rule)this.ruleDao.get(Rule.class, id);
		List<RuleDetailDTO> files = new ArrayList<RuleDetailDTO>();
		for (RuleDetail detail : rule.getDetails()) {
			RuleDetailDTO ddo = new RuleDetailDTO();
			BeanUtils.copyProperties(detail, ddo);
			files.add(ddo);
		}
		return JsonUtil.toString(files);
	}
	
	@Transactional(readOnly = true)
	public String getChannel() {
		Channel chan = (Channel)this.ruleDao.findUniqueByProperty(Channel.class, "namespace", ElementConst.GZZDCONST);
		List<Channel> channels = this.ruleDao.findAll(Channel.class, null, Restrictions.eq("parent.id", chan.getId()));
		List<ComboDTO> dtos = new ArrayList<ComboDTO>();
		for (Channel channel : channels) {
			ComboDTO dto = new ComboDTO();
			dto.setId(channel.getId());
			dto.setStr(channel.getName());
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

	@Transactional(readOnly = true)
	public String getUser() {
		List<User> users = this.ruleDao.findAll(User.class, null);
		List<ComboDTO> dtos = new ArrayList<ComboDTO>();
		for (User user : users) {
			ComboDTO dto = new ComboDTO();
			dto.setId(user.getId());
			dto.setStr(user.getTruename());
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

	@Transactional
	public String addOrEdit(HttpServletRequest request, RuleDTO params, String[] files) {
		Rule rule = null;
		if (params.getId() == null) {
			rule = new Rule();
			User user = (User)this.ruleDao.findUniqueByProperty(User.class, "username", RequestUtil.getUsername());
			rule.setUser(user);
		} else {
			rule = (Rule)this.ruleDao.get(Rule.class, params.getId());
		}
		rule.setLevel(params.getLevel());
		rule.setReleaseDate(DateUtil.format(params.getReleaseDate()));
		rule.setUpdateDate(new Date());
		rule.setState(params.getState());
		rule.setTitle(params.getTitle());
		rule.setTxt(params.getTxt());
		Channel channel = (Channel)this.ruleDao.get(Channel.class, params.getChannel());
		rule.setChannel(channel);
		this.ruleDao.addOrEdit(rule);
		Set<RuleDetail> details = rule.getDetails();
		Map<String, RuleDetail> detMap = new HashMap<String, RuleDetail>();
		if (details != null && details.size() > 0) {
			for (RuleDetail detail : details) {
				detMap.put(detail.getUrl(), detail);
			}
		}
		if (files != null && files.length > 0) {
			for (String file : files) {
				String[] ffs = file.split(";");
				if (detMap.containsKey(ffs[1])) {
					RuleDetail detail = detMap.get(ffs[1]);
					if (!ffs[0].equals(detail.getTitle())) {
						detail.setTitle(ffs[0]);
						this.ruleDao.saveOrUpdate(ffs);
					}
					detMap.remove(ffs[1]);
				} else {
					RuleDetail detail = new RuleDetail();
					detail.setRule(rule);
					detail.setTitle(ffs[0]);
					detail.setUrl(ffs[1]);
					this.ruleDao.save(detail);
				}
			}
		}
		rule.setDetails(null);
		String rootPath = request.getSession().getServletContext().getRealPath(ElementConst.SOURCESPATH);
		for (RuleDetail detail : detMap.values()) {
			FileUtil.delete(rootPath + File.separator + detail.getUrl());
			this.ruleDao.delete(detail);
		}
		return JsonUtil.toRes("保存成功！");
	}

	@Transactional
	public String remove(HttpServletRequest request, Integer id) {
		Rule rule = (Rule)this.ruleDao.get(Rule.class, id);
		Set<RuleDetail> details = rule.getDetails();
		String rootPath = request.getSession().getServletContext().getRealPath(ElementConst.SOURCESPATH);
		for (RuleDetail detail : details) {
			FileUtil.delete(rootPath + File.separator + detail.getUrl());
		}
		this.ruleDao.remove(rule);
		return JsonUtil.toRes("删除成功！");
	}
	
	@Transactional
	public String upload(HttpServletRequest request) {
		MultipartHttpServletRequest mulrequest = (MultipartHttpServletRequest)request;
		CommonsMultipartFile file = (CommonsMultipartFile)mulrequest.getFile("fileupload");
		if (file.getSize() > 0) {
			DiskFileItem fileItem = (DiskFileItem) file.getFileItem();
			String fileStr = fileItem.getName().substring(fileItem.getName().lastIndexOf(".")).toLowerCase();
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss")+ fileStr;
			String rootPath = request.getSession().getServletContext().getRealPath(ElementConst.SOURCESPATH);
			String path = rootPath + File.separator + FileUtil.getPath(fileName) + File.separator;
			File targetDir = new File(path);
			if (!targetDir.exists()) targetDir.mkdirs();
			try {
				FileCopyUtils.copy(file.getBytes(), new File(path + fileName));
				return JsonUtil.toRes("上传成功！", FileUtil.getPath(fileName) + "/" + fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return JsonUtil.toRes("上传失败！");
	}
	
}
